package com.inspinia.base.pagination;

import com.inspinia.base.pagination.Paginable;

public class SimplePage<T> implements Paginable, java.io.Serializable {
    public static final int DEF_COUNT = 10;
    private static final long serialVersionUID = 1L;
    protected long totalCount = 0;
    protected int pageSize = 10;
    protected int pageNo = 1;
    protected long totalPage = 0;

    public SimplePage() {
    }

    public SimplePage(int pageNo, int pageSize, long totalCount) {
        this(pageNo, pageSize);
        setTotalCount(totalCount);
    }

    public SimplePage(int pageNo, int pageSize) {
        if (pageSize <= 0) {
            this.pageSize = DEF_COUNT;
        } else {
            this.pageSize = pageSize;
        }
        if (pageNo <= 0) {
            this.pageNo = 1;
        } else {
            this.pageNo = pageNo;
        }
    }

    @Override
    public int getPageNo() {
        return pageNo;
    }

    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }

    @Override
    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Override
    public long getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(long totalCount) {
        if (totalCount <= 0) {
            this.totalCount = 0;
        } else {
            this.totalCount = totalCount;
            if ((this.pageNo - 1) * this.pageSize >= totalCount) {
                this.pageNo = Math.toIntExact(totalCount / pageSize);
            }
        }
    }

    @Override
    public long getTotalPage() {
        long totalPage =totalCount / pageSize;
        if (totalCount % pageSize != 0 || totalPage == 0) {
            totalPage++;
        }
        if (totalCount == 0) {
            totalPage = 0;
        }
        return totalPage;
    }

    public void setTotalPage(long totalPage) {
        this.totalPage = totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = Long.valueOf(totalPage);
    }

    @Override
    public boolean isFirstPage() {
        return pageNo <= 1;
    }

    @Override
    public boolean isLastPage() {
        return pageNo >= getTotalPage();
    }

    @Override
    public int getNextPage() {
        if (isLastPage()) {
            return pageNo;
        } else {
            return pageNo + 1;
        }
    }

    @Override
    public int getPrePage() {
        if (isFirstPage()) {
            return pageNo;
        } else {
            return pageNo - 1;
        }
    }

}
